package com.hoopchina.ui.home;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLConnection;
import java.util.ArrayList;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View.OnClickListener;
import java.util.List;
import org.apache.http.util.ByteArrayBuffer;
import android.app.AlertDialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnCreateContextMenuListener;
import android.view.View.OnTouchListener;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.HorizontalScrollView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.hoopchina.news.R;
import com.hoopchina.meta.NewsItem;
import com.hoopchina.service.BaiduNews;
import com.hoopchina.service.NewsService;
import com.hoopchina.settings.SettingsActivity;
import com.hoopchina.ui.details.DetailsView;
import com.hoopchina.ui.details.FavoritesEngine;
import com.hoopchina.ui.details.MyFavoritesView;
import com.hoopchina.ui.home.CategoryBar.OnSubItemClickListener;
import com.hoopchina.ui.main.BaseActivity;
import com.hoopchina.ui.main.ILocalNewsChanged;
import com.hoopchina.ui.main.INewsListViewObserver;
import com.hoopchina.ui.main.NewsListView;
import com.hoopchina.ui.main.NewsListView.OnRefreshListener;
import com.hoopchina.ui.main.RefreshTip;
import com.hoopchina.ui.main.TabBarButtonId;
import com.hoopchina.ui.main.ViewManager;
import com.hoopchina.ui.main.WeatherBox;
import com.hoopchina.ui.search.SearchView;
import com.hoopchina.util.DialogUtils;
import com.hoopchina.util.NetUtil;
import com.hoopchina.util.UrlUtils;
import com.hoopchina.util.download.DownloadMgr;
import com.hoopchina.util.xml.NewsItemXML;
import com.hoopchina.util.xml.XMLDataNetwork;
import com.hoopchina.weibo.ui.BindingDBEngine;
import com.hoopchina.weibo.ui.ForwardingView;
import com.hoopchina.weibo.ui.WeiboAuthActivity;



/**
 * GoalHi
 * home版块
 * 
 *@author Neusoft
 */
public class HomeView extends BaseActivity implements INewsListViewObserver,ILocalNewsChanged {

    public static final String     Id            = "BasketBall";
    private static final String		PREFS_NAME			= "MyPrefsFile";
    private SharedPreferences mSettings = null;  
	private static final int INIT_LIST_POSITION = 20;
	//private ArrayList<NewsItem> mData;
	private NewsListView mListView;
	
	private DownloadMgr mDownloadMgr = DownloadMgr.getInstance();
	private TextView mTxtView;
	private RefreshTip mRefreshTip;
	private int mCurrentPosition;
//	private String mSavePath = "/sdcard/hoopnews/offline/";
//	private TitleBar mTitleBar;
//	private ProgressBar mProgressBar;
//	private TextView mType;
//	private TextView mPercent;
//	private TextView mCounter;
//	private ImageView mImg;
	private CategoryBar mCategoryNaviBar;
//	private boolean initcalled;
//	private boolean isaway;
	
	public static List<NewsItem> mNewsList;


	// 设置收藏页的保存文件
	//private File savefile = new File("/data/data/com.hoopchina/files/save.xml");
//	private static final String mLOCAL_PATH="/data/data/com.hoopchina/files/";
	private static String[] newitems;

	//private static List<String> list = null;
	private final String FILE_NAME = "category.txt";// 确定要操作文件的文件名
//	private final String SAVE_FILE_NAME = "save.xml";
	private File file = new File("/data/data/com.hoopchina/files/category.txt");
	boolean needload = false;
	private ImageView mBaiduNewsLogo;
	private String	 mCurrentCityCode= null;
//	private String   mCurrentCity=null;
	private CityEngine mCityEngine;
	//设置新闻保存在SD卡中的路径
	private final String	 FILE_PATH= "/sdcard/hoopnews/newstempfile/";
	//消息返回状态
	private static  final int NetLoadSucess = 1;
	private static final int  NetLoadFailed = 2;
	private static final int  NetLoadMoreFailed=5;
	private static final int  NetLoadMoreSucess=6;
	//当前板块和url的初始值
	public static String mCurrentWindow=UrlUtils.HOME_ITEMS[0];	
	private String mCurrentUrl=UrlUtils.HOME_NEWS_URLS[0];
    //设置首页显示参数
	private static final int mCount=20; //焦点新闻首页显示条数
	private static final int mMorePageCount=20;//每次more增加条数
	private int mCurrentRefreshNumber=0;

	
	//刷新间隔时间
	private static final Long INTERVAL_TIME=1800000l;
	
	private int mFirstPageCount=mCount;//当前板块首页显示数量
	private FavoritesEngine OperationDB;
	private boolean mRefreshCheck=false;
	public  static boolean mRefreshLocalNewsKey=false;
	
	//private HomeSearchBar  mHomeSearchBar;
	
	/**
	 * 设置占位图的显隐
	 */
	private  void setLogoStatus(){
		if (mNewsList==null||mNewsList.size()==0) {
			mListView.setVisibility(View.INVISIBLE);
			mBaiduNewsLogo.setVisibility(View.VISIBLE);
		}else {
			mListView.setVisibility(View.VISIBLE);
			mBaiduNewsLogo.setVisibility(View.INVISIBLE);
		}
	}
	/**
	 * 内部handler类，对返回的消息进行处理
	 */
	private Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {

			switch (msg.what) {
			case NetLoadSucess: 
				mListView.setDataList(mNewsList,true);
				mListView.setSelection(0);
				if (eventStatus==Event_Refresh) {
						if (mCurrentWindow.equals(UrlUtils.HOME_ITEMS[0])||mCurrentWindow.equals(UrlUtils.HOME_ITEMS[1])) {
							//refreshTip();
						}
						eventStatus=-1;
					}
				break;
			case NetLoadFailed:
				break;
			case NetLoadMoreFailed:
				mListView.setLoadMoreButtonText(R.string.app_list_view_load_more_button);
				mListView.setLoadMoreProgressBarVisibility(View.INVISIBLE);
				mListView.setLoadMoreButtonEnable(true);
				//Toast.makeText(getApplicationContext(), "加载更多失败", 1).show();
				break;
			case NetLoadMoreSucess:
				mListView.setLoadMoreButtonText(R.string.app_list_view_load_more_button);
				mListView.setLoadMoreProgressBarVisibility(View.INVISIBLE);				
				mListView.notifyDataSetChanged();
				mListView.setLoadMoreButtonEnable(true);
				break;
			default:
				break;
			}
			mViewManager.showRefreshButton(true);
			setLogoStatus();
			
		}
	};

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.homeview);
        mCityEngine=new CityEngine(this);
        mListView = ( NewsListView )findViewById( R.id.listviewNewsListView );
        mBaiduNewsLogo = (ImageView) findViewById(R.id.baidunewslogo);
     //   mProgressBar = (ProgressBar) findViewById(R.id.loadingListProgressBar);
        //获得增加更多提示条
        mRefreshTip=(RefreshTip) findViewById(R.id.refreshtip);
        mRefreshTip.setVisibility(View.INVISIBLE);
    	OperationDB= new FavoritesEngine(this);
        if( file.exists()){
        	loadResource();
        }
        else
        {
          mCategoryNaviBar = (CategoryBar)findViewById( R.id.main_navibar );
          final ArrayList<String> catName = new ArrayList<String>();
          int itemsLen=UrlUtils.HOME_ITEMS.length;
          for (int i = 0; i < itemsLen; i++) {
          catName.add( UrlUtils.HOME_ITEMS[i] );
          }
          mCategoryNaviBar.addItemAll( catName );
        }
        
        mCategoryNaviBar.setOnSubItemClickListener( new OnSubItemClickListener() {
            
            @Override
            public void onSubItemClickListener( int position ) {
            	int itemsLen=UrlUtils.HOME_ITEMS.length;
                if ( mCategoryNaviBar.getButton( position ).getText().equals(UrlUtils.HOME_ITEMS[itemsLen-1]) )
                {
            		mViewManager.showClearOnTopView(DragListActivity.Id, DragListActivity.class, true, null);
            		mViewManager.setTabBarVisibility(false);

                }
                else
                {
                	//在这里处理版不同板块的点击事件
                	clearCategoryNaviBarBackground(position);
                	mCurrentWindow=mCategoryNaviBar.getButton( position ).getText().toString();
                	setCurrentWindowUrl();
                	if (mCurrentUrl!=null) {
                		getNewsListForNeed(true);
                		//Toast.makeText( GoalHi.this, mCategoryNaviBar.getButton( position ).getText(), 1000 ).show();
					}else {
						//Toast.makeText( GoalHi.this, mCategoryNaviBar.getButton( position ).getText()+"...该接口调试中", 1000 ).show();
					}

                	
                }
                
            }
        });
        
        mListView.setOnRefreshListener( new OnRefreshListener() {
            
            @Override
            public void onRefresh() {
                new GetDataTask().execute( );
            }
        });
        
        mListView.setObserver( this );
        mListView.setOnCreateContextMenuListener(new OnCreateContextMenuListener() {
			@Override
			public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
				//take user operation trace
				AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo;
				if (info.position != 0) {
					menu.setHeaderTitle("新闻功能");
					menu.add(0, 0, 0, "查看");
					menu.add(0, 1, 0, "转发");
					menu.add(0, 2, 0, "收藏");

				}
			}
		});
        
        LayoutInflater inflater = LayoutInflater.from(getBaseContext());
		View titlebarview = inflater.inflate( R.layout.titlebar, null );
		
        mTxtView = (TextView)titlebarview.findViewById(R.id.txtTitleBarTitle);
        mTxtView.setClickable(true);
        mTxtView.setOnClickListener(new OnClickListener() {
    	    @Override
    	    public void onClick(View v) {
             mListView.scrollTo(0, INIT_LIST_POSITION);
    	    }
    	});
        

        mViewManager.setTabBarVisibility( true );
        
        mSettings = getSharedPreferences(PREFS_NAME, 0); 
        if (mSettings == null || mSettings.getBoolean("user_guide_home", true)) { 
	        mViewManager.setUserGuideImage(R.drawable.image_guide_home_view);
	        mViewManager.setUserGuideOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					SharedPreferences.Editor editor = mSettings.edit();  
					editor.putBoolean("user_guide_home", false);  
					editor.commit();  
			        mViewManager.setUserGuideVisibility(ImageButton.GONE);
				}
			});
	        mViewManager.setUserGuideVisibility(ImageButton.VISIBLE);
        }
        else {
	        mViewManager.setUserGuideVisibility(ImageButton.GONE);

		}
		initCurrentWindow();
		//initcalled = true;

	}
    private class GetDataTask extends AsyncTask<Void, Void, String[]> {

        @Override
        protected String[] doInBackground(Void... params) {
            // Simulates a background job.
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                ;
            }
            return null;
        }

        @Override
        protected void onPostExecute(String[] result) {
            mListView.notifyDataSetChanged();
            // Call onRefreshComplete when the list has been refreshed.
            mListView.onRefreshComplete();

            super.onPostExecute(result);
        }
    }
    
	//初始化当前窗口的方法
	private void initCurrentWindow() {
		setLogoStatus();
		if (NetUtil.checkNet(this)) {
			getNewsListForNeed(true);
		} else {
			alertNetError();
		}
	}
	
	private int alertRefresh=0;
	/*
	 * 网络未连接时的提示方法
	 */
	private void alertNetError() {
		AlertDialog.Builder ab=new AlertDialog.Builder(HomeView.this);
		ab.setTitle("网络错误");
		ab.setMessage("网络检查错误，设置网络或加载本地");
		ab.setPositiveButton("设置网络", new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				//该变量记录跳转到设置网络的页面
				alertRefresh=1;
				Toast.makeText(mViewManager.getCurrentActivity(),"请显示网络已连接后再返回" , 1).show();
				Intent intent=new Intent(android.provider.Settings.ACTION_WIRELESS_SETTINGS);
				HomeView.this.startActivity(intent);
				
			}
		});
		ab.setNegativeButton("取消", new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				loadLocalResource();
				if (mNewsList!=null) {
					mListView.setDataList(mNewsList,true);
				}
			}
		});
		ab.show();
	}
	/*
	 * 把当前类别文字转化成相应url
	 */
	private void setCurrentWindowUrl(){
		int itemLen=UrlUtils.HOME_ITEMS.length;
		for (int i = 0; i < itemLen; i++) {
			if (mCurrentWindow.equals(UrlUtils.HOME_ITEMS[i])) {
				mCurrentUrl=UrlUtils.HOME_NEWS_URLS[i];
			}
		}
	}
	/*
	 * listview上条目点击事件
	 */
	@Override
	public void onNewsListItemClick(AdapterView<?> parent, View view,
			int position, long id) {
		goToDetailsView(position+1);
    }
	/*
	 * listview上条目长按事件
	 */
	@Override
	public void onNewsListItemLongClick(AdapterView<?> parent, View view,
			int position, long id) {
		// Toast.makeText( this, "long click:"+position, 600 ).show();
		mCurrentPosition = position;
	}

	// private void appendData() {
	// for ( int i = 0; i < 20; ++i ) {
	// NewsItem item = new NewsItem();
	// item.setAbs( "abs" );
	// item.setAuthor( "author" );
	// item.setImgUrl( "imgUrl" );
	// item.setTime( "time" );
	// item.setTitle( "title" );
	// item.setUrl( "url" );
	//
	// // item.Image = ResourceUtils.getRoundedCornerBitmap(
	// // ( ( BitmapDrawable )getResources().getDrawable( R.drawable.sample1 )
	// ).getBitmap(),
	// // 90, 60, 5, 0xff424242 );
	// // item.Name = String.format( getString( R.string.test_placeName ),
	// iItemCount + i );
	// // item.Distance = String.format( getString( R.string.test_placeDistance
	// ), i * 10 );
	// iData.add( item );
	// }
	// iAdapter.notifyDataSetChanged();
	// }
    @Override
	protected void onStart() {
		super.onStart();
		if (alertRefresh==1) {
			initCurrentWindow();
			alertRefresh=0;
		}
	}
	@Override
	public void onResume() {
	
		super.onResume();
		mViewManager.setAssistButton("",
				R.drawable.titlebar_btn_refresh_selector,
				new OnClickListener() {
					@Override
					public void onClick(View v) {
						getNewsListForNeed(false);
					}
				});
		mViewManager.showRefreshButton(true);
		mViewManager.setTitle(getString(R.string.app_title_news_home));
		mViewManager.displayWeatherBox(true);
		mViewManager.showDetailViewBar(false);
		mCategoryNaviBar.showArrowButton();
		clearCategoryNaviBarBackground(mCurrentPosition);
		mViewManager.hideLeftButton();
		mViewManager.setTabBarVisibility(true);
		mViewManager.setTitleBarVisibility(true);
		if (file.exists()) {
			RefreshResource();
		}else {
			mCategoryNaviBar.setFocusedButton(mCategoryNaviBar.mLastPosition);
		}
		mViewManager.refreshWeatherBoxCity();
		mViewManager.setTabBarVisibility(true);
		mViewManager.setTitleBarVisibility(true);
      //  isaway = false;
        
        if (mRefreshCheck) {
        	mRefreshCheck=false;
        	mListView.notifyDataSetChanged();
        	//mListView.refreshScrollListener();
        	mListView.setLoadMoreButtonVisibility(View.VISIBLE);
		}
        if (mRefreshLocalNewsKey) {
			if (mCurrentWindow.equals(UrlUtils.HOME_ITEMS[1])) {
				mRefreshLocalNewsKey=false;
				refreshLocalNewsList();
			}
		}
        
    }
    

	
	@Override
    protected void onDestroy() {
        super.onDestroy();
    }

	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		menu.clear();
		MenuInflater inflater = getMenuInflater();
		if(mCurrentWindow.equals(UrlUtils.HOME_ITEMS[1])){
			inflater.inflate(R.menu.homeview_menu, menu);
    	}else {
    		inflater.inflate(R.menu.homeview, menu);
		}
		
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.menu_homeview_refresh:
			getNewsListForNeed(false);
			break;

            case R.id.menu_homeview_custom_section:
            	if(mCurrentWindow.equals(UrlUtils.HOME_ITEMS[1])){
            		mViewManager.citySelect(WeatherBox.News_Place_Selected,this);
            	}else {
            		mViewManager.showClearOnTopView(DragListActivity.Id, DragListActivity.class, true, null);
            		mViewManager.setTabBarVisibility(false);
				}
                break;

            case R.id.menu_homeview_favorites:
    			Bundle bundle = new Bundle();
    			bundle.putString("LaunchType", "FromHomeListMenu");
           		mViewManager.showClearOnTopView(MyFavoritesView.Id, MyFavoritesView.class, true, bundle);
        		mViewManager.setTabBarVisibility(false);
                break;
            
            case R.id.menu_homeview_offline_download:
            mDownloadMgr.setContext( this );
            mDownloadMgr.enQueue( mCurrentUrl,mCurrentWindow,mCurrentCityCode );
               break;
               
            case R.id.menu_homeview_user_guide:
            	
          	        mViewManager.setUserGuideImage(R.drawable.image_guide_home_view);
          	        mViewManager.setUserGuideOnClickListener(new OnClickListener() {
          				
          				@Override
          				public void onClick(View v) {
          					SharedPreferences.Editor editor = mSettings.edit();  
          					editor.putBoolean("user_guide_home", false);  
          					editor.commit();  
          			        mViewManager.setUserGuideVisibility(ImageButton.GONE);
          				}
          			});
          	        mViewManager.setUserGuideVisibility(ImageButton.VISIBLE);
                
               break;
              
            case R.id.menu_homeview_settings:
            	
//            mViewManager.showView(SettingsActivity.Id, SettingsActivity.class, true, null);
             
  			  Intent intent = new Intent();
  			  intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
              intent.setClass(HomeView.this, SettingsActivity.class);
  			  startActivity(intent);

//            mViewManager.showView(SubscribePageActivity.Id, SubscribePageActivity.class, true, null);
               break;
            
            case R.id.menu_homeview_exit:
            	DialogUtils.showExitDialog(this);
               break;
            
            default:
               break;
            }
            return false;
    }
    /*
     * 加载本地新闻类别文件
     */
    private void loadResource()
    {
        InputStream is = null;
   		try {
   			is = openFileInput(FILE_NAME);
   		} catch (FileNotFoundException e) {
   			// TODO Auto-generated catch block
   			e.printStackTrace();
   		}//创建写入流
           BufferedInputStream bis = new BufferedInputStream(is);  
           ByteArrayBuffer baf = new ByteArrayBuffer(100);  
           int current = 0;  
           try {
   			while((current = bis.read()) != -1) {  
   			    baf.append((byte)current);  
   			}
   		} catch (IOException e) {
   			// TODO Auto-generated catch block
   			e.printStackTrace();
   		}  
          String myString = new String(baf.toByteArray());
        //  list = new ArrayList<String>();
          Log.d("--------filepath-----", myString );
          String substring = myString.substring(myString.lastIndexOf("[")+1, myString.lastIndexOf("]"));
          newitems = substring.split(", "); 
          Log.d("--------filepath-----", substring );
          int length = newitems.length;
           
           mCategoryNaviBar = (CategoryBar)findViewById( R.id.main_navibar );
           final ArrayList<String> catName = new ArrayList<String>();
          // catName.clear();
           for (int i = 0; i < length; i++) {
               catName.add( newitems[i] );
           }
           catName.remove(getResources().getString(R.string.app_home_draglistactivity_navigation));
           catName.remove(getResources().getString(R.string.app_home_draglistactivity_more));
           catName.add(getResources().getString(R.string.app_home_homeview_self_navigation));
           mCategoryNaviBar.addItemAll( catName );
    }

    
    private void RefreshResource()
    {
        InputStream is = null;
   		try {
   			is = openFileInput(FILE_NAME);
   		} catch (FileNotFoundException e) {
   			// TODO Auto-generated catch block
   			e.printStackTrace();
   		}//创建写入流
           BufferedInputStream bis = new BufferedInputStream(is);  
           ByteArrayBuffer baf = new ByteArrayBuffer(100);  
           int current = 0;  
           try {
   			while((current = bis.read()) != -1) {  
   			    baf.append((byte)current);  
   			}
   		} catch (IOException e) {
   			// TODO Auto-generated catch block
   			e.printStackTrace();
   		}  
          String myString = new String(baf.toByteArray());
        //  list = new ArrayList<String>();
          Log.d("--------filepath-----", myString );
          String substring = myString.substring(myString.lastIndexOf("[")+1, myString.lastIndexOf("]"));
          newitems = substring.split(", "); 
          Log.d("--------filepath-----", substring );
          int length = newitems.length;
           
           mCategoryNaviBar = (CategoryBar)findViewById( R.id.main_navibar );
           final ArrayList<String> catName = new ArrayList<String>();
           //catName.clear();
           for (int i = 0; i < length; i++) {
               catName.add( newitems[i] );
           }
           catName.remove(getResources().getString(R.string.app_home_draglistactivity_navigation));
           catName.remove(getResources().getString(R.string.app_home_draglistactivity_more));
           catName.add(getResources().getString(R.string.app_home_homeview_self_navigation));
           mCategoryNaviBar.refreshItemAll( catName ); 
           int pos=0;
           for (int i = 0; i < catName.size(); i++) {
        	   if (catName.get(i).trim().equals(mCategoryNaviBar.mLastPositionString)) {
				   pos=i;
				   break;
        	   }
           }
           mCategoryNaviBar.setFocusedButton(pos);
    }  
    
    /*
     * 点击后，listview跳到第一条
     */
	@Override
	public void clickToTop() {
		 mListView.setSelection(0);
	}


    @Override
    protected void onPause() {
        super.onPause();
        mViewManager.displayWeatherBox(false);
        mViewManager.showLoadingProgressBar(false);
        mViewManager.showAssistButton(false);
        mViewManager.setUserGuideVisibility(ImageButton.GONE);
       // isaway = true;
    }
    /*
     * 点击listview最上边的输入框，跳转到搜索页面
     * @see com.hoopchina.ui.main.INewsListViewObserver#onNewsListHeaderClick(android.widget.AdapterView, android.view.View, int, long)
     */
	@Override
	public void onNewsListHeaderClick(AdapterView<?> parent, View view,
			int position, long id) {
		mViewManager.showViewAndChangeTab( SearchView.Id,  SearchView.class, null, TabBarButtonId.ESEARCH );
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case 0:
			goToDetailsView(mCurrentPosition);
			break;
		case 1:
            final CharSequence[] items = {
            		  getResources().getString(R.string.forward_select_item_sina)
            		, getResources().getString(R.string.forward_select_item_tencent)
            		, getResources().getString(R.string.forward_select_item_sohu)
            		, getResources().getString(R.string.forward_select_item_netease)
            		, getResources().getString(R.string.forward_select_item_renren)}; 
            AlertDialog.Builder builder = new AlertDialog.Builder(HomeView.this);
            builder.setTitle(getResources().getString(R.string.forward_select_dialog_title));
            builder.setItems(items, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int item) {
	        	   if (!NetUtil.checkNet(HomeView.this)) {
	        			Toast.makeText(mViewManager.getCurrentActivity(),
	        					getResources().getString(R.string.app_no_network),
	        					Toast.LENGTH_SHORT).show();
	        	   }
	        	   else
	        	   {
	                   Bundle aBundle = new Bundle();
	                   aBundle.putInt("WeiboType", item);
	                   aBundle.putString("Title", mNewsList.get(mCurrentPosition-1).getTitle());
	                   aBundle.putString("ImageUrl", mNewsList.get(mCurrentPosition-1).getImgUrl());
	                   aBundle.putString("NewsUrl", mNewsList.get(mCurrentPosition-1).getUrl());
	                   aBundle.putString("Abstract", mNewsList.get(mCurrentPosition-1).getAbs());
	                   aBundle.putString("Author", mNewsList.get(mCurrentPosition-1).getAuthor());
	                   aBundle.putBoolean("FromBindingPage", false);
	                   
		           		BindingDBEngine mEngine = new BindingDBEngine(HomeView.this);
		         		if ( mEngine.isBinding( item ) ) {
		         			ForwardingView.setOldView(HomeView.Id, HomeView.class);
		                     ViewManager.getInstance().showClearOnTopView( ForwardingView.Id,
		                     		ForwardingView.class, false, aBundle);
		         		} else {
		         			WeiboAuthActivity.setOldView(HomeView.Id, HomeView.class);
		                     ViewManager.getInstance().showClearOnTopView(WeiboAuthActivity.Id,
		                    		 WeiboAuthActivity.class, false, aBundle);
		         		}
	        	   }
                }
            });
            builder.create().show();
			break;			
		case 2:	    	
	    	Cursor cursor = OperationDB.queryByTitle(mNewsList.get(mCurrentPosition-1).getTitle());
    		if ( cursor.getCount() == 0 )
    		{
    			String Time;
    			if (HomeView.mCurrentWindow==UrlUtils.HOME_ITEMS[0]) {
    				//焦点新闻用的发行时间字段
    				Time = mNewsList.get(mCurrentPosition-1).getmPublicTime();
    			}else {
    				Time = mNewsList.get(mCurrentPosition-1).getTime();
    			}
    			
    			Toast.makeText(this, getString( R.string.app_save_sucess ), 2000).show();	
    	    	OperationDB.insert(mNewsList.get(mCurrentPosition-1).getUrl(), 
    	    			mNewsList.get(mCurrentPosition -1).getTitle(), 
    	    			mNewsList.get(mCurrentPosition -1).getAbs(), 
    	    			mNewsList.get(mCurrentPosition-1).getAuthor(), 
    	    			Time,
    	    			mNewsList.get(mCurrentPosition-1).getImgUrl());
    		}else
    		{
    			Toast.makeText(this, getString( R.string.app_cannot_save_again ), 2000).show();
    		}
    		cursor.close();
			break;
		default:
			break;
		}	
			
			return super.onContextItemSelected(item);
	}
	/*
	 * 跳转到新闻详细的方法
	 */
    private void goToDetailsView(int position)
    {
    	mRefreshCheck=true;
    	
    	Bundle bundle = new Bundle();
		bundle.putInt("NewPosition", position-1);
		bundle.putInt("Type", 0);
		bundle.putString("NewsType", mCurrentWindow);
		
 		mViewManager.setTabBarVisibility(false);
 		mViewManager.setTitleBarVisibility(false);
        mViewManager.showClearOnTopView( DetailsView.Id, DetailsView.class, true, bundle); 
    }

	
	//下边参数进行方法跟踪判断
	private static final int Event_Code_Local_Net=1;
	private static final int Event_Refresh=2;
	private int eventStatus=-1;
	/**
	 * 加载本地数据后刷新或刷新
	 * @param isAuto 选择功能分支
	 */
	private void getNewsListForNeed(boolean isAuto){
		if (isAuto) {
			//事件发起者
			eventStatus=Event_Code_Local_Net;
			loadLocalResource();
			
			if (mNewsList==null||mRefreshLocalNewsKey) {
				setLogoStatus();
				refreshNewsList();
			}else {
				mListView.setDataList(mNewsList,true);
				mListView.setSelection(0);
				//刷新策略
				String currentFileSaveName=UrlUtils.getNameFromUrl(mCurrentUrl);
				long lastTime=mSettings.getLong(currentFileSaveName, -1);
				if (lastTime==-1||lastTime!=-1&&System.currentTimeMillis()-lastTime>=INTERVAL_TIME) {
					refreshNewsList();
					//Toast.makeText(getApplicationContext(), "刷新成功", 1).show();
				}else {
					//Toast.makeText(getApplicationContext(), "还剩余"+(INTERVAL_TIME-(System.currentTimeMillis()-lastTime))/60000+"分可自动刷新", 1).show();
				}
			}
		}else {
			if (NetUtil.checkNet(this)) {
				eventStatus=Event_Refresh;
				refreshNewsList();
			}else {
				Toast.makeText(getApplicationContext(), "你的网络出现异常", 1).show();
			}
			
		}
	}
	/**
	 * 加载本地XML新闻资源
	 */
	private void loadLocalResource() {
		String fileName=UrlUtils.getNameFromUrl(mCurrentUrl);

		try {
			InputStream instreamChannelInfo = null;

			File files = new File(FILE_PATH, fileName);
			if (files.exists()) {

				instreamChannelInfo = new FileInputStream(FILE_PATH + "/"+ fileName);
				List<NewsItem> temList=NewsItemXML.getNewsList(instreamChannelInfo);
				 if (temList!=null&&temList.size()>0) {
				    	mNewsList=temList;
				    	setLogoStatus();
					}else {
						mNewsList=null;
					}
			}else {
				mNewsList=null;
			}
			
		} catch (Exception e) {
			mNewsList=null;
		}
	}
	/**
	 * 加载网络新闻资源
	 */
	public void refreshNewsList() {
		//保存当前时间
		String currentFileSaveName=UrlUtils.getNameFromUrl(mCurrentUrl);
		Editor editor=mSettings.edit();
		editor.putLong(currentFileSaveName, System.currentTimeMillis());
		editor.commit();
		
		mViewManager.showRefreshButton(false);
		NewsService.getTheadPool(true).submit(new Runnable() {
			
			@Override
			public void run() {
				
				String fileSaveName=UrlUtils.getNameFromUrl(mCurrentUrl);
				String cateWindow=mCurrentWindow;
				List<NewsItem> temtList=null;
				try {
					String urlCon="http://news.hoopchina.com/news.xml";		
					URLConnection Urlconnection=XMLDataNetwork.getHttpConnection(mCurrentUrl);
					temtList=NewsItemXML.getNewsList(Urlconnection.getInputStream());
                     
					if (temtList!=null&&temtList.size()>0&&cateWindow.equals(mCurrentWindow)) {
						//此下代码为计算更新的条数
					//	mCurrentRefreshNumber=findNewCount(mNewsList,temtList);
						mNewsList=FormatListData(temtList);;
						mHandler.sendEmptyMessage(NetLoadSucess);
						BaiduNews.localSave( mNewsList,FILE_PATH ,fileSaveName);
					}else {
						temtList.clear();
						mHandler.sendEmptyMessage(NetLoadFailed);
					}
					
					
				} catch (Exception e) {
					mHandler.sendEmptyMessage(NetLoadFailed);
				}
				
			}

			
		});
		
	}
	
	protected List<NewsItem> FormatListData(List<NewsItem> aNewsList) {
        if (mCurrentWindow==UrlUtils.HOME_ITEMS[0]){
		for(int i=0; i<aNewsList.size();i++)
		{
			if ( aNewsList.get(i).getAbs().contains("img src ='"))
					{
				   // String imgUrl = aNewsList.get(i).getAbs().substring(aNewsList.get(i).getAbs().lastIndexOf("http"), aNewsList.get(i).getAbs().lastIndexOf(".jpg'"));
				     aNewsList.get(i).setImgUrl(aNewsList.get(i).getAbs().substring(aNewsList.get(i).getAbs().lastIndexOf("=\'")+2, aNewsList.get(i).getAbs().lastIndexOf("jpg\'")+3));
				    aNewsList.get(i).setAbs(aNewsList.get(i).getAbs().substring(aNewsList.get(i).getAbs().lastIndexOf("jpg'")+9));
					}
			else {
			     aNewsList.get(i).setAbs(aNewsList.get(i).getAbs().substring(aNewsList.get(i).getAbs().indexOf(">")+1));
			}
			
		}
        }
		
		return aNewsList;
	}
	/**
	 * 计算新集合返回的新条数
	 * @param mNewsItems  老集合
	 * @param temtList   新集合
	 * @return          新返回的条数
	 */
//	private int findNewCount(List<NewsItem> mNewsItems,List<NewsItem> temtList) {
//		int k=0;
//		if (mNewsItems==null||mNewsItems.size()==0) {
//			k=temtList.size();
//		}else {
//			long temFirstTime=Long.valueOf(temtList.get(0).getTime());
//			long temLastTime=Long.valueOf(temtList.get(temtList.size()-1).getTime());
//			long mainFirstTime=Long.valueOf(mNewsItems.get(0).getTime());
//			if(temLastTime>mainFirstTime){
//				k=temtList.size();
//			}else if (temFirstTime==mainFirstTime) {
//				k=0;
//			}else {
//				
//				for (int i = 0; i < temtList.size(); i++) {
//					long temTime=Long.valueOf(temtList.get(i).getTime());
//					if (temTime!=mainFirstTime) {
//						k++;
//					}else {
//						break;
//					}
//				}
//			}
//		}
//		return k;
//	}
	/*
	 * 加载更多，加载条数由上边常量参数设定
	 */
	private void getMoreList()
	{
		mViewManager.showRefreshButton(false);
		NewsService.getTheadPool(true).submit(new Runnable() {
			
			@Override
			public void run() {
				String fileSaveName=UrlUtils.getNameFromUrl(mCurrentUrl);
				String cateWindow=mCurrentWindow;
				List<NewsItem> temtList=null;
				String urlCon=mCurrentUrl+"&rn="+mMorePageCount+"&time="+mNewsList.get(mNewsList.size()-1).getTime();
				try {
		
						URLConnection Urlconnection=XMLDataNetwork.getHttpConnection(urlCon);
						temtList=NewsItemXML.getNewsList(Urlconnection.getInputStream());
					if (temtList!=null&&temtList.size()>0&&mCurrentWindow.equals(cateWindow)) {
						mNewsList.addAll(temtList);
						temtList.clear();
						mHandler.sendEmptyMessage(NetLoadMoreSucess);
						BaiduNews.localSave( mNewsList,FILE_PATH, fileSaveName);
					}else {
						temtList.clear();
						mHandler.sendEmptyMessage(NetLoadMoreFailed);
					}
				} catch (Exception e) {
					mHandler.sendEmptyMessage(NetLoadMoreFailed);
				}
			}
		});
		
	}
	/*
	 * 清理CategoryNaviBar背景
	 */
	void clearCategoryNaviBarBackground(int currentposition){
//		for(int i = 0; i < mCategoryNaviBar.getButtonList().size(); i++ )
//		{
//			if( i != currentposition )
//			{
//				mCategoryNaviBar.getButton(i).setBackgroundResource(0);
//			}
//		}
	}

	/*
	 * 点击刷新加载更多
	 */
	@Override
	public void onClickLoadMoreButton() {
			mListView.setLoadMoreButtonEnable(false);
			mListView.setLoadMoreButtonText(R.string.remind_loading_baidu_news);
			mListView.setLoadMoreProgressBarVisibility(View.VISIBLE);
		    getMoreList();
		

	}
	/*
	 * 列表到底端时自动加载更多
	 */
	@Override
	public void autoLoadMoreList() {
		 getMoreList();
	}
	/*
	 * 获得当前城市编号
	 */
//	private boolean getCityCode(){
//		boolean isCityChanged=false;
//		if(null == mSettings)
//            return isCityChanged;
//		String temCityCode="0";
//		String temCity=CitySettingDialog.HTTP_DEFAULT_CITY;
//		temCity = mSettings.getString("mCurrentCityNews", CitySettingDialog.HTTP_DEFAULT_CITY);
//		if (temCity!=null) {
//			temCityCode = mCityEngine.getCityCode(temCity);
//		}
//		if (!temCity.equals(mCurrentCity)) {
//			isCityChanged=true;
//			mCurrentCity=temCity;
//			mCurrentCityCode=temCityCode;
//		}
//		return isCityChanged;
//	}

	@Override
	public void refreshLocalNewsList() {

		loadLocalResource();
		setLogoStatus();
		if (mNewsList==null||mNewsList.size()==0) {
			refreshNewsList();
		}else {
			mListView.setDataList(mNewsList,true);
			mListView.setSelection(0);
			refreshNewsList();
		}
	}
	
	


}
